package com.dingtao.common;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MyActivity implements Application.ActivityLifecycleCallbacks {

    private List<Activity> acts;
    private static final String finish_all_activity = "finish_all_activity";

    public MyActivity(Context context) {
        this. acts = new ArrayList<>();
        IntentFilter inf =new IntentFilter();
        inf.addAction(finish_all_activity);
        MyBroadcast broadcast = new MyBroadcast();
        context.registerReceiver(broadcast,inf);
    }

    public static void finishAllActivity(Context context){
        Intent it = new Intent();
        it.setAction(finish_all_activity);
        context.sendBroadcast(it);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        acts.add(activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        acts.remove(activity);
    }

    class MyBroadcast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (finish_all_activity.equals(intent.getAction())){
                for (Activity act : acts) {
                    act.finish();
                }
            }

        }
    }
}
